﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataAccessLayer;
using DataTransferObject;

namespace BusinessLogicLayer
{
    public class TypeBLL:BLLBase
    {
        private readonly Ibn_dm_TypeDAL _dal;
        public TypeBLL(string connectionString = "")
            : base(connectionString)
        {
            this._dal = new bn_dm_TypeDAL(this.DatabaseFactory);
        }

        public IQueryable<TypeDto> Get(int facilityId, string key = "")
        {
            var query = this._dal.GetAll()
                .Where(e => e.Id == facilityId)
                .Select(e => new TypeDto
                    {
                        Id = e.Id,
                        Ten = e.Ten,
                    });

            if (!string.IsNullOrEmpty(key))
            {
                query = query.Where(e => e.Ten.StartsWith(key));
            }
            return query;
        }
        public List<TypeDto> GetAll()
        {
            var query = this._dal.GetAll()
                .Select(e => new TypeDto
                {
                    Id = e.Id,
                    Ten = e.Ten,
                });
            return query.ToList();
        }
        public IQueryable<TypeDto> Query()
        {
            var query = this._dal.GetAll()
                .Select(e => new TypeDto
                {
                    Id = e.Id,
                    Ten = e.Ten,
                });
            return query;
        }
        public void Update(TypeDto dto, int facilityId)
        {
            var entity = this._dal.GetAll().FirstOrDefault(e => e.Id == dto.Id && e.Id == facilityId);
            if (entity == null) throw new Exception("Đối tượng không tồn tại");
            entity.Ten = dto.Ten;
            this.SaveChanges();
        }
        public void Insert(TypeDto dto, int facilityId)
        {
            var entity = new bn_dm_Type();
            entity.Ten = dto.Ten;
            this._dal.Add(entity);
            this.SaveChanges();
            dto.Id = entity.Id;
        }
        public void Delete(int id, int facilityId)
        {
            var entity = this._dal.GetAll().FirstOrDefault(e => e.Id == id && e.Id == facilityId);
            if (entity == null) throw new Exception("Đối tượng không tồn tại");
            this._dal.Delete(entity);
            this.SaveChanges();
        }
    }
}
